import React, {Component} from 'react'
import {request, changeToArr, moment} from '../../common/js/utils'
import { Avatar, Button, Cascader, Select, Form, message, Modal, Input, Checkbox } from 'antd'
import DefaultLayout from '../../layouts/default_layout'
import {setUserInfo} from '../../actions'
import {connect} from 'react-redux'
import {STORAGE_TYPE} from '../../common/js/storage_type'
import propTypes from 'prop-types'
import * as R from 'ramda'
import './home.scss'
import {addActivity, getActivities, gift, updateActivities} from '../../common/js/activities'
const CheckboxGroup = Checkbox.Group
const Option = Select.Option
const Item = Form.Item

function mapStateToProps(state, props) {
  return {
    userInfo: state.userInfo,
    servers: state.servers
  }
}

const mapDispatchToProps = dispatch => {
  return {
    setUserInfo(value) {
      dispatch(setUserInfo(value))
    }
  }
}

const activities = getActivities()

@connect(mapStateToProps, mapDispatchToProps)
@Form.create()
class Home extends Component {

  state = {
    roles: [],
    logs: [],
    activities: activities,
    s_activities: activities.filter(item => item.checked).map(item => item.iActivityId),
    isLoading: false
  }

  getUserInfo = () => {
    const cookie = window.datas.cookieMap
    request({
      methods: 'get',
      url: 'http://qfwd.qq.com/',
      params: {
        uin: cookie.uin && cookie.uin.substr(2), // 登录用户QQ号
        skey: cookie.skey, // 好像是用户登录凭证，在cookie里储存
        refresh: 0, // 不知道
        func: 'loginAll', // 回调函数
        ran: Math.random() // 随机数
      }
    }).then(res => {
      try {
        res = JSON.parse(res.replace(/(loginAll\()|(\);)/g, ''))
        if (Number(res.result) === 0) {
          this.addLog({
            content: `${res.nick} 登陆成功！`
          })
          this.props.setUserInfo(res)
          this.handleServer()
          this.echoBack()
        } else {
          this.addLog({
            content: res
          })
        }
      } catch (err) {
        this.addLog({
          content: err.message,
          style: {color: 'red'}
        })
      }
    })
  }

  login = () => {
    window.ipcRenderer.send('login')
  }

  componentWillMount() {
    const datas = window.datas
    if (datas.cookieMap.skey) {
      this.getUserInfo()
    } else {
      this.addLog({
        content: 'skey 用户未登录',
        style: {color: 'red'}
      })
    }
    window.ipcRenderer.on('login-success', this.getUserInfo)
  }

  echoBack = () => {
    const history = JSON.parse(localStorage.getItem(STORAGE_TYPE.server))
    if (history) {
      this.props.form.setFieldsValue({
        server: history.server
      })
    }
  }

  componentDidMount() {
    this.echoBack()
  }

  componentWillUnmount() {
    window.ipcRenderer.removeListener('login-success', this.getUserInfo)
  }

  handleServer = () => {
    const values = this.props.form.getFieldsValue().server
    if (values && values.length > 1) {
      request({
        url: 'http://comm.aci.game.qq.com/main',
        params: {
          game: 'bns', // 游戏简称
          area: values[1], // 大区id
          sCloudApiName: 'ams.gameattr.role', // 应该是后台接口名
          sServiceDepartment: 'group_5',
        }
      }).then(res => {
        // eslint-disable-next-line
        const f = new Function(`${res}return query_role_result`)
        const d = f()
        if (d.retCode === 0) {
          // 处理角色数据
          let extraData = {}
          const data = decodeURIComponent(d.data)
          let arr = data.split('&')[1].split('|')
          arr.splice(0, 1)
          arr = arr.map(item => {
            let a = item.split(' ')
            return {
              name: a[1],
              value: a[0]
            }
          })
          this.setState({roles: arr}, () => {
            if (this.isEcho) return
            const history = JSON.parse(localStorage.getItem(STORAGE_TYPE.server))
            if (history) {
              this.props.form.setFieldsValue({
                role: history.role
              })
            }
            this.isEcho = true
          })
          extraData.md5str = d.md5str // 提交活动需要的md5校验码
          extraData.checkparam = encodeURIComponent(d.checkparam) // 提交活动需要的校验参数
          this.props.setUserInfo(Object.assign({}, this.props.userInfo, extraData))
        }
      })
    }
  }

  onSubmit = async () => {
    if (!gift.isStop && this.state.isLoading) {
      gift.isStop = true
      this.isCancel = true
      message.loading('正在停止...', 0)
      return
    }
    const values = this.props.form.getFieldsValue()
    if (!values.server || !values.role) {
      message.error('请选择大区和角色')
      return
    }
    if (!this.props.userInfo.nick) {
      this.login()
      return
    }
    localStorage.setItem(STORAGE_TYPE.server, JSON.stringify(values))
    const acts = this.actList.getValue()
    const list = this.state.activities.slice(0)
    list.forEach(item => item.checked = acts.indexOf(item.iActivityId) !== -1)
    try {
      updateActivities(list)
    } catch (err) {
      this.addLog({
        content: err.message,
        style: {color: 'red'}
      })
    }
    const userInfo = {
      area: values.server[1],
      role: values.role,
      ...this.props.userInfo
    }
    gift.log = this.addLog
    gift.activities = list
    gift.userInfo = userInfo
    gift.isStop = false
    this.setState({
      isLoading: true,
      logs: []
    })
    this.isCancel = false
    try {
      await gift.start()
    } catch (e) {
      this.addLog({
        content: e.message,
        style: {color: 'red'}
      })
    }
    gift.isStop = true
    this.setState({isLoading: false})
    if (this.isCancel) {
      message.destroy()
      message.success('已停止')
    } else {
      this.addLog({
        content: `领取完毕 ${moment(new Date()).format('YYYY-MM-DD HH:mm:ss')}  -By ChenJiYuan`,
        style: {color: 'green'}
      })
    }
  }

  addLog = (arr) => {
    arr = changeToArr(arr)
    this.setState({
      logs: R.concat(this.state.logs, arr)
    }, () => {
      const dom = this.refs.scrollView
      const con = this.refs.list
      if (dom && con) {
        dom.scrollTop = con.clientHeight
      }
    })
  }

  addAct = () => {
    this.addModal.show()
  }

  render() {
    const {userInfo, servers} = this.props
    const {roles, logs, activities, s_activities, isLoading} = this.state
    const {getFieldDecorator} = this.props.form
    return (
      <DefaultLayout
        header={
          <div className="home-header">
            <div className="flex-row align-center justify-between">
              <div className="act-list">
                <ActList log={this.addLog} wrappedComponentRef={wrap => this.actList = wrap} defaultValue={s_activities} options={activities} />
              </div>
              <div style={{width: '48%'}}>
                <div className="top">
                  <div className="top-left">
                    <Avatar src={userInfo.Face} >{userInfo.nick ? null : '空'}</Avatar>
                    <span className={'nick'}>{userInfo.nick || '未登录'}</span>
                  </div>
                  <div className="top-right">
                    <Button size="small" type="primary" onClick={this.login} style={{fontSize: 12}}>登录/切换用户</Button>
                  </div>
                </div>
                <Form className="server-pick">
                  <Item
                    style={{ width: '48%' }}
                  >
                    {
                      getFieldDecorator('server')(
                        <Cascader
                          fieldNames={{ label: 't', value: 'v', children: 'opt_data_array' }}
                          options={servers}
                          placeholder="选择服务器"
                          displayRender={(label) => label[label.length - 1]}
                          onChange={e => setTimeout(this.handleServer, 100)}
                        />
                      )
                    }
                  </Item>
                  <Item
                    style={{ width: '48%' }}
                  >
                    {
                      getFieldDecorator('role')(
                        <Select
                          placeholder={'选择角色'}
                          allowClear
                        >
                          {
                            roles.map((item, key) => (
                              <Option key={key} value={item.value}>{item.name}</Option>
                            ))
                          }
                        </Select>
                      )
                    }
                  </Item>
                </Form>
                <div className={'submit'}>
                  <Button type={'primary'} style={{width: '48%'}} onClick={this.onSubmit} ghost={isLoading}>{isLoading ? '取消' : '一键领取'}</Button>
                  <Button type={'primary'} ghost style={{width: '48%'}} onClick={this.addAct}>添加活动</Button>
                </div>
              </div>
            </div>
          </div>
        }
      >
        <div className={'home-log'}>
          <div className={'list'} ref={'scrollView'}>
            <div ref={'list'}>
              {
                logs.map((val, key) => (
                  <p key={key} style={val.style}>{val.content}</p>
                ))
              }
            </div>
          </div>
        </div>
        <AddAct log={this.addLog} wrappedComponentRef={modal => this.addModal = modal} parent={this} />
      </DefaultLayout>
    )
  }
}

@Form.create()
class AddAct extends Component {

  state = {
    visible: false
  }

  handleOk = async () => {
    const values = this.props.form.getFieldsValue()
    if (values.website) {
      this.setState({visible: false})
      try {
        const activities = await addActivity(values.website, this.props.log)
        this.props.parent.setState({activities})
      } catch (err) {
        this.props.log({
          content: err.message,
          style: {color: 'red'}
        })
      }
    }
  }

  onCancel = () => {
    this.setState({visible: false})
  }

  show = () => {
    this.setState({visible: true})
  }

  render() {
    const {getFieldDecorator} = this.props.form
    return (
      <Modal
        title="活动添加"
        visible={this.state.visible}
        onOk={this.handleOk}
        onCancel={this.onCancel}
        centered
      >
        {
          getFieldDecorator('website')(
            <Input placeholder={'请输入活动网址/活动ID-活动名称'} />
          )
        }
      </Modal>
    )
  }
}
AddAct.propsTypes = {
  log: propTypes.func
}

@Form.create()
class ActList extends Component {

  getValue = () => {
    const values = this.props.form.getFieldsValue()
    return values.activities
  }

  render() {
    const {defaultValue, options} = this.props
    const {getFieldDecorator} = this.props.form
    return (
      getFieldDecorator('activities', {
        initialValue: defaultValue
      })(
        <CheckboxGroup options={options.map(item => {
          return {
            label:
              <span title={`截止日期：${item.dtBeginTime} 至 ${item.dtEndTime}`}>{item.title}</span>
            ,
            value: item.iActivityId
          }
        })} />
      )
    )
  }
}
ActList.propsTypes = {
  defaultValue: propTypes.array,
  options: propTypes.array,
  log: propTypes.func
}

export default Home
